package com.project.baseTest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.List;

public class ShiroTest {


    public ShiroTest(){
//        //创建安全管理器
//        DefaultSecurityManager manager=new DefaultSecurityManager();
//        //设置数据源。为类路径下的shiro.ini
//        manager.setRealm(new IniRealm("classpath:shiro.ini"));
//        //设置安全管理器
//        SecurityUtils.setSecurityManager(manager);
//        //得到主体
//       Subject subject =SecurityUtils.getSubject();
//       //产生用户名密码的令牌
//        UsernamePasswordToken token=new UsernamePasswordToken("tam","123");
//       //登陆认证
//       subject.login(token);
//        System.out.println("登陆成功");

        DefaultSecurityManager manager = new DefaultSecurityManager();
        manager.setRealm(new CustomRealm());
        SecurityUtils.setSecurityManager(manager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("tam", "123");
try{
    subject.login(token);
    System.out.println("成功");
    //查看是否有当前角色
    System.err.println(subject.hasRole("manager"));
    //查看是否有当前这些角色
    System.err.println(subject.hasAllRoles(List.of("manager", "order")));
    //查看是否有权限
    System.err.println(subject.isPermitted("user:create"));
    System.err.println(subject.isPermitted("user:del"));
//查看是否拥护这些权限
    System.err.println(subject.isPermittedAll("user:create", "order:add"));
    System.err.println(subject.isPermittedAll("user:create", "product:add"));

}catch (UnknownAccountException e1){
    System.out.println("用户名错误");

}catch (IncorrectCredentialsException e2){
    System.out.println("密码错误");

}




    };


    public static void main(String[] args) {
        new ShiroTest();
    }
}
